package com.kgt.crud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kgt.crud.bean.Employee;
import com.kgt.crud.bean.Msg;
import com.kgt.crud.service.EmployeeService;

import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition;


import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理员工CRUD 请求
 */
@Controller
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value="/emp",method= RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){
        if(!employeeService.checkuser(employee.getEmpName())){
            return Msg.fail().add("va_msg","用户名重复");
        }

        if(result.hasErrors()){
            //校验失败，应该返回失败，在模态框中显示校验失败的错误信息
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                System.out.println("错误的字段名："+fieldError.getField());
                System.out.println("错误信息："+fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        }else{
            employeeService.saveEmp(employee);
            return Msg.success();
        }

    }

    @RequestMapping("/checkuser")
    @ResponseBody
    public Msg checkuser(@RequestParam("empName")String empName){
     /* String regEmpName="^([\\u4e00-\\u9fa5]+|([a-z]+[\\s\\.]?)+)";
        if(!empName.matches(regEmpName)){
            return Msg.fail().add("va_msg","用户名可以是2-5位中文或者6-16位英文和数字的组合");
        }*/

        if(employeeService.checkuser(empName)){
            return Msg.success().add("va_msg","用户名可用");
        }
        return Msg.fail().add("va_msg","用户名重复");

    }

    @RequestMapping("/getemps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo){
        PageHelper.startPage(pageNo, 5);
        List<Employee> employees = employeeService.getAll();
        /*for (Employee employee:employees){
            System.out.println(StringEscapeUtils.unescapeHtml4(employee.getEmpName()));
           employee.setEmpName(StringEscapeUtils.unescapeHtml4(employee.getEmpName()));
        }*/

        PageInfo pageInfo = new PageInfo(employees,5);
        return Msg.success().add("pageInfo",pageInfo);
    }

    /**
     * 查询员工数据 分页
     *
     * @return
     */
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                          Model model) {
        //引入PageHelper分页插件
        //在查询之前调用，传入页码 以及页面大小
        PageHelper.startPage(pageNo, 5);
        //startPage后面紧跟的就是一个分页查询
        List<Employee> employees = employeeService.getAll();
        //使用PageInfo包装查询后的结果 只要将PageInfo交给页面就行了
        //传入连续显示的页数
        PageInfo pageInfo = new PageInfo(employees,5);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }
}

